<template>
  <ul class="category-panel" @mouseleave="hideCategory">
    <li
      @mouseover="() => setupCurrentProducts(item.key)"
      class="category-item"
      v-for="item in categories"
    >
      {{ item.label }}
      <n-icon size="28" color="#fdfdfddd" style="font-weight: bold;">
        <KeyboardArrowRightFilled></KeyboardArrowRightFilled>
      </n-icon>
    </li>
  </ul>
  <section
    @mouseenter="keepCategory"
    @mouseleave="hideCategory"
    v-show="showCategory"
    class="category-products-container"
  >
    <PicName class="product" v-for="product in currentProducts.products" :key="product.pro_no" :product="product"></PicName>
  </section>
</template>
<script setup lang="ts">
import { KeyboardArrowRightFilled } from '@vicons/material';
import { computed, shallowReactive, ref } from '@vue/reactivity';
import { getCategories, getProducts } from '../../api/productApi';
import PicName from '../product/PicName.vue';

const categories = getCategories().slice(1);

const mouseOnCategory = ref(false);
const showCategory = computed(() => {
  return !!currentProducts.products && mouseOnCategory.value;
})
const productsMap = new Map;
const currentProducts = shallowReactive<any>({
  products: null,
});

let fetching: any = null;
let leaving: any = null;
function setupCurrentProducts(key: any) {
  if (!key) return;
  mouseOnCategory.value = true;
  clearTimeout(fetching);
  clearTimeout(leaving);
  if (productsMap.get(key)) return currentProducts.products = productsMap.get(key);
  fetching = setTimeout(() => {
    getProducts({
      cid: key,
      limit: 20,
    }).then((res) => {
      currentProducts.products = res.data || [];
      productsMap.set(key, currentProducts.products);
    })
  }, 100);
}

function hideCategory() {
  leaving = setTimeout(() => {
    mouseOnCategory.value = false;
  }, 300)
}

function keepCategory() {
  clearTimeout(leaving);
  mouseOnCategory.value = true;
}
</script>
<style scoped>
.category-panel {
  min-width: 240px;
  background-color: #3d3d3d77;
  height: 100%;
  position: absolute;
  left: 0;
  z-index: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

.category-products-container {
  min-width: 250px;
  position: absolute;
  left: 240px;
  z-index: 1;
  background-color: #f7f7f7;
  height: 100%;
  box-shadow: 6px 6px 18px 4px #3f3f3f33;
  display: grid;
  grid-template-rows: repeat(6, 90px);
  grid-auto-flow: column;
  justify-items: flex-start;
  align-items: center;
  padding-right: 10px;
}

.product {
  margin-left: 10px;
}

.category-item {
  height: 40px;
  display: flex;
  width: 100%;
  box-sizing: border-box;
  justify-content: space-between;
  padding: 0 24px;
  font-size: 14px;
  color: #fdfdfd;
  align-items: center;
}

.category-item:hover {
  background-color: #18a058;
  cursor: pointer;
}
</style>